package com.lzx.iteam;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.*;
import android.view.animation.*;
import android.widget.*;
import com.lzx.iteam.adapter.ApprovalFgAdapter;
import com.lzx.iteam.adapter.ApprovalGridAdapter;
import com.lzx.iteam.adapter.AttendanceTeamAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.ApprovalData;
import com.lzx.iteam.bean.ApprovalGroupData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetApprovalList;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 04月 07日
 * Time: 下午2:41
 *
 * @QQ : 1234567890
 * **********************************
 */
public class ApprovalActivity extends MyBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    @FindViewById(id = R.id.approval_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id=R.id.approval_ll_help)
    private LinearLayout mLayoutHelp;
    @FindViewById(id = R.id.approval_ll_create)
    private LinearLayout mLayoutCreate;
    @FindViewById(id = R.id.approval_tv_my)
    private TextView mTvApply;
    @FindViewById(id = R.id.approval_tv_ap)
    private TextView mTvApproval;
    @FindViewById(id = R.id.approval_line_my)
    private View mViewApply;
    @FindViewById(id = R.id.approval_line_ap)
    private View mViewAp;
    @FindViewById(id = R.id.approval_vp)
    private ViewPager mVp;
    @FindViewById(id = R.id.approval_ll_more)
    private LinearLayout mLayoutComplete;
    @FindViewById(id = R.id.approval_ll_team)
    private LinearLayout mLayoutTeam;
    @FindViewById(id = R.id.approval_tv_team)
    private TextView mTvTeam;
    @FindViewById(id = R.id.approval_iv_arrow)
    private ImageView mIvArrow;
    @FindViewById(id = R.id.rl_title_bar)
    private RelativeLayout mLayoutBar;
    @FindViewById(id = R.id.tv_approval_red_dot)
    private TextView mTvApprovalCount;
    @FindViewById(id = R.id.approval_tv_no_team)
    private TextView mTvNoApproval;


    private List<String> mApprovalType;
    private PopupWindow mCreatePop;
    private GridView mGridView;
    private ApprovalGridAdapter mCreateAdapter;
    private List<Fragment> mFragmentList = new ArrayList<Fragment>();;
    private ApprovalFgAdapter mFgAdapter;
    private Dialog mTeamDialog;
    private ApprovalFragment fragment3;
    private ArrayList<Object> mGroupDatas;
    private ApprovalGroupData mGroup;
    private String mGroupId;
    private int mPage;

    private final int GET_APPROVOL_LIST = 10001;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case GET_APPROVOL_LIST:
                    if (msg.arg1 == 0) {
                        mGroupDatas = (ArrayList<Object>) msg.obj;
                        if (mGroupDatas.size() > 0) {
                            mLayoutTeam.setVisibility(View.VISIBLE);
                            mTvNoApproval.setVisibility(View.GONE);
                            mGroupId = mPreferenceUtil.getString(PreferenceUtil.APPROVAL_GROUP_ID,"");
                            if (!StringUtil.isEmpty(mGroupId)){
                                for (int i = 0;i<mGroupDatas.size();i++){
                                    ApprovalGroupData attendance = (ApprovalGroupData) mGroupDatas.get(i);
                                    if (mGroupId.equals(attendance.getGroup_id())){
                                        mGroup = attendance;
                                        break;
                                    }
                                }
                            }
                            if (StringUtil.isEmpty(mGroupId) || mGroup == null){
                                mGroup = (ApprovalGroupData) mGroupDatas.get(0);
                                mGroupId = mGroup.getGroup_id();
                            }
                            mTvTeam.setText(mGroup.getGroup_name());

                        } else {
                            mLayoutTeam.setVisibility(View.GONE);
                            mTvNoApproval.setVisibility(View.VISIBLE);
                        }
                        Log.d("My_Test","    handleMessage    ");
                        initFragment();

                    } else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }

        }
    };

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle, R.layout.approval_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mLayoutHelp.setOnClickListener(this);
        mLayoutCreate.setOnClickListener(this);
        mTvApply.setOnClickListener(this);
        mTvApproval.setOnClickListener(this);
        mLayoutComplete.setOnClickListener(this);
        mLayoutTeam.setOnClickListener(this);

    }

    @Override
    public void initData() {
        mApprovalType = new ArrayList<String>();
        mApprovalType.add(getString(R.string.approval_travel));
        mApprovalType.add(getString(R.string.approval_leave));
        mApprovalType.add(getString(R.string.approval_out));
        /*mApprovalType.add(getString(R.string.approval_sign));*/
        mCreateAdapter = new ApprovalGridAdapter(mApprovalType, mActivity);
//        getAttendanceFace();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getApprovalGroups();
    }

    private void initFragment(){
        mFragmentList.clear();
        ApprovalFragment fragment1 = ApprovalFragment.newInstance(mGroupId, 1);
        ApprovalFragment fragment2 = ApprovalFragment.newInstance(mGroupId, 2);
        mFragmentList.add(fragment1);
        mFragmentList.add(fragment2);
        mFgAdapter = new ApprovalFgAdapter(getSupportFragmentManager(), mActivity, mFragmentList);
        mVp.setAdapter(mFgAdapter);
        mVp.setCurrentItem(mPage);
        mVp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (i == 0) {
                    mTvApply.setTextColor(getResources().getColor(R.color.ap_title_blue));
                    mTvApproval.setTextColor(getResources().getColor(R.color.schedule_content));
                    mViewApply.setVisibility(View.VISIBLE);
                    mViewAp.setVisibility(View.GONE);
                    mLayoutComplete.setVisibility(View.GONE);
                    mPage = 0;
                } else {
                    mTvApproval.setTextColor(getResources().getColor(R.color.ap_title_blue));
                    mTvApply.setTextColor(getResources().getColor(R.color.schedule_content));
                    mViewAp.setVisibility(View.VISIBLE);
                    mViewApply.setVisibility(View.GONE);
                    mLayoutComplete.setVisibility(View.VISIBLE);
                    mPage = 1;
                }

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.approval_ll_back:
                finish();
                break;
            case R.id.approval_ll_help:
                Intent intent=new Intent(this,WebViewActivity.class);
                intent.putExtra("title","如何发出审批申请?");
                intent.putExtra("type",3);
                startActivity(intent);
                break;
            case R.id.approval_ll_create:
                showCreatePop();
                break;
            case R.id.approval_tv_my:
                mPage = 0;
                mVp.setCurrentItem(0);
                mLayoutComplete.setVisibility(View.GONE);
                break;
            case R.id.approval_tv_ap:
                mPage = 1;
                mVp.setCurrentItem(1);
                mLayoutComplete.setVisibility(View.VISIBLE);
                break;
            case R.id.approval_ll_more:
                fragment3 = ApprovalFragment.newInstance(mGroupId, 3);
                getSupportFragmentManager()
                        .beginTransaction()
                        .setCustomAnimations(R.anim.slide_right_in, R.anim.slide_left_out)
                        .add(R.id.layout_content, fragment3)
                        .addToBackStack(null)
                        .commitAllowingStateLoss();
                break;
            case R.id.approval_ll_team:
                if (mIvArrow.getDrawable().getCurrent().getConstantState()
                        .equals(getResources().getDrawable(R.drawable.arrow_up).getConstantState())) {
                    mIvArrow.setImageResource(R.drawable.arrow_down);
                } else {
                    mIvArrow.setImageResource(R.drawable.arrow_up);
                    showTeamDialog();
                }
                break;
        }

    }

    /**
     * 弹出中间团队选择
     */
    private void showTeamDialog() {

        mTeamDialog = new AlertDialog.Builder(mActivity)
                .create();
        mTeamDialog.show();
        Window window = mTeamDialog.getWindow();
        WindowManager.LayoutParams lp = mTeamDialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha=0.5f; // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.attendance_team_pop_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.Ap_Pop_Style);

        ListView listView = (ListView) window.findViewById(R.id.lv_attendance_team_list);
        AttendanceTeamAdapter adapter = new AttendanceTeamAdapter(this);
        adapter.bindData(mGroupDatas,1);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mGroup = (ApprovalGroupData) mGroupDatas.get(i);
                mGroupId = mGroup.getGroup_id();
                mPreferenceUtil.save(PreferenceUtil.APPROVAL_GROUP_ID,mGroupId);
                mTvTeam.setText(mGroup.getGroup_name());
                mTeamDialog.dismiss();
                mFgAdapter.update(0,mGroupId);
                mFgAdapter.update(1,mGroupId);

            }
        });

        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.dialog_cancel);

        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTeamDialog.dismiss();
            }
        });
        mTeamDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mIvArrow.setImageResource(R.drawable.arrow_down);
            }
        });

    }


    /**
     * 创建审批popupwindow
     */
    private void showCreatePop() {

        View view = LayoutInflater.from(mActivity).inflate(R.layout.approval_create_pop, null);
        mGridView = (GridView) view.findViewById(R.id.create_approval_gv);
        mGridView.setAdapter(mCreateAdapter);
        mGridView.setOnItemClickListener(this);
        mGridView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        RelativeLayout cancel = (RelativeLayout) view.findViewById(R.id.create_rl_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCreatePop.dismiss();
            }
        });

        mCreatePop = new PopupWindow();
        mCreatePop.setBackgroundDrawable(new BitmapDrawable());
        mCreatePop.setFocusable(true);
        mCreatePop.setTouchable(true);
        mCreatePop.setOutsideTouchable(true);
        mCreatePop.setContentView(view);
        mCreatePop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mCreatePop.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        mCreatePop.showAtLocation(view, Gravity.CENTER, 0, 0);
        mCreatePop.update();
        view.startAnimation(AnimationUtils.loadAnimation(mActivity, R.anim.alpha_in));

        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mCreatePop.dismiss();
                return false;
            }
        });

    }

    public void removeFragment() {
        getSupportFragmentManager()
                .beginTransaction()
                .setCustomAnimations(R.anim.slide_left_in, R.anim.slide_right_out)
                .remove(fragment3)
                .addToBackStack(null)
                .commitAllowingStateLoss();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (StringUtil.isEmpty(mGroupId)){
            showShortToast("您不在考勤组里面，不能发起审批");
        }else{
            Intent intent = new Intent(mActivity, ApprovalCreateActivity.class);
            ApprovalData approvalData = new ApprovalData();
            approvalData.setApproval_type(position + 1);
            approvalData.setApproval_group_id(mGroupId);
            intent.putExtra("approvalData", approvalData);
            intent.setAction("create_approval");
            startActivity(intent);
        }
        mCreatePop.dismiss();

    }

    /**
     * 用户考勤面板, 可能每个团队下有一个考勤界面，这里列出全部，客户端选择第一个展示即可
     */
    private void getApprovalGroups() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        GetApprovalList msg = new GetApprovalList(mHandler.obtainMessage(GET_APPROVOL_LIST));
        msg.mApi = AsynHttpClient.KEY_APPROVAL_MY_GROUPS;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    public void setNewMsg(int status){
        if (status == 0) {
            mTvApprovalCount.setVisibility(View.GONE);
        } else {
            mTvApprovalCount.setVisibility(View.VISIBLE);
            if (status > 0 && status < 10) {
                ViewGroup.LayoutParams linearParams = mTvApprovalCount.getLayoutParams();
                int pd = Constants.dip2px(mActivity, 16);
                linearParams.width = pd;
                linearParams.height = pd;
                mTvApprovalCount.setLayoutParams(linearParams);
                mTvApprovalCount.setBackgroundResource(R.drawable.unread_1);
                mTvApprovalCount.setGravity(Gravity.CENTER);
                mTvApprovalCount.setText(status + "");
            } else if (status >= 10 && status < 100) {
                ViewGroup.LayoutParams linearParams = mTvApprovalCount.getLayoutParams();
                int widthPx = Constants.dip2px(mActivity, 24);
                int heightPx = Constants.dip2px(mActivity, 16);
                linearParams.width = widthPx;
                linearParams.height = heightPx;
                mTvApprovalCount.setLayoutParams(linearParams);
                mTvApprovalCount.setBackgroundResource(R.drawable.unread_2);
                mTvApprovalCount.setText(status + "");
            } else if (status >= 100) {
                ViewGroup.LayoutParams linearParams = mTvApprovalCount.getLayoutParams();
                int widthPx = Constants.dip2px(mActivity, 34);
                int heightPx = Constants.dip2px(mActivity, 16);
                linearParams.width = widthPx;
                linearParams.height = heightPx;
                mTvApprovalCount.setLayoutParams(linearParams);
                mTvApprovalCount.setBackgroundResource(R.drawable.unread_3);
                mTvApprovalCount.setText("99+");
            }
        }
    }


    @Override
    public void onBackPressed() {
        if (fragment3 != null && fragment3.isVisible()){
            removeFragment();
        }else{
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("My_Test","    onDestroy    ");
        mHandler.removeCallbacksAndMessages(null);
    }
}
